from datetime import datetime, timedelta
from Crypto.Cipher import AES  # pycryptodome
from Crypto.Util.Padding import pad, unpad
import base64


def ok(data='', msg: str = "请求成功", ):
    return {'code': 0, 'msg': msg, 'data': data, 'success': True}


def fail(msg: str = "请求失败", data=None, err=None):
    return {'code': -1, 'msg': msg, 'data': data, 'error': str(err) if err else '', 'success': False}


def str_to_date(str_date, fomat='%Y-%m-%d %H:%M:%S'):
    return datetime.strptime(str_date, fomat)


def date_to_str(dateobj, fomat='%Y-%m-%d %H:%M:%S'):
    return dateobj.strftime(fomat)


def get_tomorrow(str_date, day):
    date_obj = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S")
    next_day = date_obj + timedelta(days=int(day))
    return next_day


def aes_encrypt(data, key="", iv=""):
    try:
        key = key if len(key) > 0 else 'wojnF5WMXfmxSYls'.encode('utf-8')
        iv = iv if len(iv) > 0 else 'xzYFodeJs0nIQ7Pa'.encode('utf-8')
        aes = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
        data = pad(data.encode('utf-8'), 16, style='pkcs7')
        data = base64.encodebytes(aes.encrypt(data))
        return data.decode('utf-8').strip()
    except:
        return ''


def aes_decrypt(data, key="", iv=""):
    try:
        key = key if len(key) > 0 else 'wojnF5WMXfmxSYls'.encode('utf-8')
        iv = iv if len(iv) > 0 else 'xzYFodeJs0nIQ7Pa'.encode('utf-8')
        aes = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
        r = aes.decrypt(base64.decodebytes(bytes(data, encoding='utf8'))).decode('utf-8')
        r = r[:-ord(r[-1])]
        return r
    except:
        return ''


def base64_encode(v):
    try:
        byte_data = v.encode('utf-8')
        encoded_data = base64.b64encode(byte_data)
        return encoded_data.decode('utf-8')
    except:
        return ''
    
def base64_decode(v):
    try:
        encoded_data = v.encode('utf-8')
        decoded_data = base64.b64decode(encoded_data)
        return decoded_data.decode('utf-8')
    except:
        return ''
    

